import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ResultUtils } from 'src/common/utils/result.utils';
import { Repository } from 'typeorm';
import { CreateLinkDto } from './dto/create-link.dto';
import { GetLinkDto } from './dto/get-link.dto';
import { UpdateLinkDto } from './dto/update-link.dto';
import { Link } from './link.entity';

@Injectable()
export class LinkService {
  constructor(@InjectRepository(Link) private linkRepository: Repository<Link>) { }
  async create(createLinkDto: CreateLinkDto) {
    const link = await this.linkRepository.create(createLinkDto);
    const result = await this.linkRepository.save(link);
    return ResultUtils.success(result.id);
  }

  async findAll(query: GetLinkDto, isAdmin: boolean) {
    let { limit, page } = query;
    const queryBuilder = this.linkRepository.createQueryBuilder('link');
    if (!isAdmin) {
      queryBuilder.andWhere('status=:status', { status: 1 });
    }
    queryBuilder.orderBy('sort', 'DESC').addOrderBy('update_time', 'DESC');
    if (page) {
      if (!limit) {
        limit = 10
      }
      queryBuilder.take(limit).skip((page - 1) * limit);
      const list = await queryBuilder.getManyAndCount();
      return ResultUtils.success({
        list: list[0],
        total: list[1]
      });
    } else {
      return ResultUtils.success(await queryBuilder.getMany());
    }
  }

  async findOne(id: number) {
    return ResultUtils.success(await this.linkRepository.findOne({ where: { id } }));
  }

  async update(id: number, updateLinkDto: UpdateLinkDto) {
    const link = await this.linkRepository.findOne({ where: { id } });
    const newLink = this.linkRepository.merge(link, updateLinkDto);
    return ResultUtils.success(await this.linkRepository.save(newLink));
  }

  async remove(id: number) {
    await this.linkRepository.delete(id);
    return ResultUtils.success();
  }
}
